package com.byit.controller;


import com.alibaba.fastjson.JSONObject;
import com.arcsoft.face.FaceInfo;
import com.byit.builder.MapBuilder;
import com.byit.domain.AppUser;
import com.byit.domain.AppUserAuthentication;
import com.byit.enums.PromptInfo;
import com.byit.face.FaceEngineService;
import com.byit.jwt.ann.JwtUser;
import com.byit.jwt.domain.JwtSession;
import com.byit.msg.MessageResult;
import com.byit.service.IAppUserAuthenticationService;
import com.byit.service.IAppUserService;
import com.byit.utils.IdcardUtil;
import com.byit.utils.MinioUtil;
import com.byit.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

/**
 * APP用户认证
 *
 * @author tjm
 * @date 2019年1月7日
 */
@RestController
@RequestMapping("/app/userAuth")
public class AppUserAuthenticationController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IAppUserAuthenticationService appUserAuthenticationService;
    @Autowired
    private FaceEngineService faceEngineService;
    @Autowired
    private IAppUserService appUserService;

    @Autowired
    private MinioUtil minioUtil;


    /**
     * 查询个人认证信息
     */
    @GetMapping("/get")
    public Object get(@JwtUser JwtSession session) {
        if (!session.isLogin()) {
            return MessageResult.warpper(PromptInfo.USER_LOGIN_INVALID);
        }
        Long userId = session.userId();
        List<AppUserAuthentication> appUserAuthentications = appUserAuthenticationService.selectByMap(
                MapBuilder.newMap(2).setParam("user_id", userId).setParam("is_del", 0).ok());
        if (appUserAuthentications.size() == 0) {
            return MessageResult.warpper(PromptInfo.ERROR_USER_AUTH_NULL);
        }
        if (appUserAuthentications.size() > 1) {
            return MessageResult.warpper(PromptInfo.ERROR_USER_AUTH_MORE);
        }
        return MessageResult.success(appUserAuthentications.get(0));
    }

    /**
     * 添加用户认证
     */
    @PostMapping("/add")
    public Object add(@JwtUser JwtSession session, @RequestParam("realName") String realName,
                      @RequestParam("idCardNo") String idCardNo,
                      @RequestParam("idCardFace") MultipartFile idCardFace,
                      @RequestParam("idCardCon") MultipartFile idCardCon,
                      @RequestParam("photo") MultipartFile photo) {
        try {
            if (!session.isLogin()) {
                return MessageResult.warpper(PromptInfo.USER_LOGIN_INVALID);
            }
            Long userId = session.userId();
            //检查身份证是否合法
            if (!IdcardUtil.validateCard(idCardNo)) {
                return MessageResult.warpper(PromptInfo.ERROR_ID_CARD);
            }
            //检查该用户是否存在认证信息
            List<AppUserAuthentication> appUserAuthentications = appUserAuthenticationService.selectByMap(
                    MapBuilder.newMap(2).setParam("user_id", userId).setParam("is_del", 0).ok());
            if (appUserAuthentications.size() > 0) {
                return MessageResult.warpper(PromptInfo.ERROR_USER_AUTH_HAVE);
            }
            //检查该身份证是否已被使用
            List<AppUserAuthentication> haveIdCards = appUserAuthenticationService.selectByMap(
                    MapBuilder.newMap(3).setParam("id_card_no", idCardNo).setParam("status", 2).setParam("is_del", 0).ok());
            if (haveIdCards.size() > 0) {
                return MessageResult.warpper(PromptInfo.ERROR_AUTH_IDCARD_HAVE);
            }
            //人脸检测
            List<FaceInfo> faceInfos = faceEngineService.detectFace(photo.getInputStream());
            if (faceInfos.size() == 0){
                return MessageResult.warpper(PromptInfo.ERROR_FACE_NULL);
            }else if (faceInfos.size() > 1){
                return MessageResult.warpper(PromptInfo.ERROR_FACE_MUCH);
            }
            AppUserAuthentication authentication = new AppUserAuthentication();
            //上传身份证正面图片
            JSONObject flg = minioUtil.uploadFile(idCardFace.getInputStream(),
                    idCardFace.getOriginalFilename().substring(idCardFace.getOriginalFilename().lastIndexOf(".")), "authentication/user/idCardFace/");
            if ("1".equals(flg.getString("flag"))) {
                return MessageResult.warpper(PromptInfo.ERROR_AUTH_PIC_UPLOAD);
            } else {
                authentication.setIdCardFace(flg.getString("path"));
            }
            //上传身份证反面图片
            JSONObject flg2 = minioUtil.uploadFile(idCardCon.getInputStream(),
                    idCardCon.getOriginalFilename().substring(idCardCon.getOriginalFilename().lastIndexOf(".")), "authentication/user/idCardCon/");
            if ("1".equals(flg2.getString("flag"))) {
                return MessageResult.warpper(PromptInfo.ERROR_AUTH_PIC_UPLOAD);
            } else {
                authentication.setIdCardCon(flg2.getString("path"));
            }
            //上传个人近期图片
            JSONObject flg3 = minioUtil.uploadFile(photo.getInputStream(),
                    photo.getOriginalFilename().substring(photo.getOriginalFilename().lastIndexOf(".")), "authentication/user/photo/");
            if ("1".equals(flg3.getString("flag"))) {
                return MessageResult.warpper(PromptInfo.ERROR_AUTH_PIC_UPLOAD);
            } else {
                authentication.setPhoto(flg3.getString("path"));
            }
            //人证对比
//            try {
//                authentication.setContrast(faceEngineService.faceCompare(photo.getInputStream(), idCardFace.getInputStream()));
//            }catch (Exception e){
//                logger.error(e.getMessage());
//            }
            authentication.setUserId(userId);
            authentication.setOperationId(userId);
            authentication.setRealName(realName);
            authentication.setIdCardNo(idCardNo);
            authentication.setCreateTime(new Date());
            authentication.setUpdateTime(new Date());
            if (appUserAuthenticationService.insert(authentication)) {
                //修改app_user表认证状态
                AppUser appUser = new AppUser();
                appUser.setId(userId);
                appUser.setAuthState(1);
                appUserService.updateById(appUser);
                return MessageResult.warpper("000", null, "个人认证信息提交成功");
            }
            return MessageResult.warpper(PromptInfo.ERROR_USER_AUTH_FILED);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return MessageResult.warpper(PromptInfo.ERROR_AUTH_PIC_UPLOAD);
        }
    }

    /**
     * 修改个人认证
     */
    @PostMapping("/update")
    public Object update(@JwtUser JwtSession session, String realName, String idCardNo,
                         MultipartFile idCardFace, MultipartFile idCardCon, MultipartFile photo) {
        try {
            if (!session.isLogin()) {
                return MessageResult.warpper(PromptInfo.USER_LOGIN_INVALID);
            }
            AppUserAuthentication authentication = new AppUserAuthentication();
            Long userId = session.userId();
            //检查该用户是否存在认证信息
            List<AppUserAuthentication> appUserAuthentications = appUserAuthenticationService.selectByMap(
                    MapBuilder.newMap(2).setParam("user_id", userId).setParam("is_del", 0).ok());
            if (appUserAuthentications.size() > 1) {
                return MessageResult.warpper(PromptInfo.ERROR_USER_AUTH_MORE);
            } else if (appUserAuthentications.size() == 0) {
                return MessageResult.warpper(PromptInfo.ERROR_USER_AUTH_NULL);
            }

            AppUserAuthentication oldAuth = appUserAuthentications.get(0);
            if (oldAuth.getStatus() != 3) {
                return MessageResult.warpper(PromptInfo.ERROR_USER_AUTH_NOT_UPDATE);
            }
            //检查该身份证是否已被使用
            if (StringUtil.isNotEmpty(idCardNo)) {
                //检查身份证是否合法
                if (!IdcardUtil.validateCard(idCardNo)) {
                    return MessageResult.warpper(PromptInfo.ERROR_ID_CARD);
                }
                List<AppUserAuthentication> haveIdCards = appUserAuthenticationService.selectByMap(
                        MapBuilder.newMap(3).setParam("id_card_no", idCardNo).setParam("status", 2).setParam("is_del", 0).ok());
                if (haveIdCards.size() > 1) {
                    return MessageResult.warpper(PromptInfo.ERROR_AUTH_IDCARD_HAVE);
                } else if (haveIdCards.size() == 1) {
                    if (!userId.equals(haveIdCards.get(0).getUserId())) {
                        return MessageResult.warpper(PromptInfo.ERROR_AUTH_IDCARD_HAVE);
                    }
                }
                authentication.setIdCardNo(idCardNo);
            }

            //上传个人近期图片
            if (null != photo) {
                //人脸检测
                List<FaceInfo> faceInfos = faceEngineService.detectFace(photo.getInputStream());
                if (faceInfos.size() == 0){
                    return MessageResult.warpper(PromptInfo.ERROR_FACE_NULL);
                }else if (faceInfos.size() > 1){
                    return MessageResult.warpper(PromptInfo.ERROR_FACE_MUCH);
                }
                JSONObject flg3 = minioUtil.uploadFile(photo.getInputStream(),
                        photo.getOriginalFilename().substring(photo.getOriginalFilename().lastIndexOf(".")), "authentication/user/photo/");
                if ("1".equals(flg3.getString("flag"))) {
                    return MessageResult.warpper(PromptInfo.ERROR_AUTH_PIC_UPLOAD);
                } else {
                    authentication.setPhoto(flg3.getString("path"));
                }
            }

            //上传身份证正面图片
            if (null != idCardFace) {
                JSONObject flg = minioUtil.uploadFile(idCardFace.getInputStream(),
                        idCardFace.getOriginalFilename().substring(idCardFace.getOriginalFilename().lastIndexOf(".")), "authentication/user/idCardFace/");
                if ("1".equals(flg.getString("flag"))) {
                    return MessageResult.warpper(PromptInfo.ERROR_AUTH_PIC_UPLOAD);
                } else {
                    authentication.setIdCardFace(flg.getString("path"));
                }
            }
            //上传身份证反面图片
            if (null != idCardCon) {
                JSONObject flg2 = minioUtil.uploadFile(idCardCon.getInputStream(),
                        idCardCon.getOriginalFilename().substring(idCardCon.getOriginalFilename().lastIndexOf(".")), "authentication/user/idCardCon/");
                if ("1".equals(flg2.getString("flag"))) {
                    return MessageResult.warpper(PromptInfo.ERROR_AUTH_PIC_UPLOAD);
                } else {
                    authentication.setIdCardCon(flg2.getString("path"));
                }
            }

            //人脸对比
//            try {
//                if (null != idCardFace && null != photo){
//                    authentication.setContrast(faceEngineService.faceCompare(photo.getInputStream(), idCardFace.getInputStream()));
//                }else if (null != idCardFace){
//                    authentication.setContrast(faceEngineService.faceCompare(minioUtil.getInputStream(oldAuth.getPhoto()), idCardFace.getInputStream()));
//                }else if (null != photo){
//                    authentication.setContrast(faceEngineService.faceCompare(photo.getInputStream(), minioUtil.getInputStream(oldAuth.getIdCardFace())));
//                }
//            }catch (Exception e){
//                logger.error(e.getMessage());
//            }
            authentication.setId(oldAuth.getId());
            if (StringUtil.isNotEmpty(realName)) {
                authentication.setRealName(realName);
            }
            authentication.setUpdateTime(new Date());
            authentication.setStatus(1);
            if (appUserAuthenticationService.updateById(authentication)) {
                //修改app_user表认证状态
                AppUser appUser = new AppUser();
                appUser.setId(userId);
                appUser.setAuthState(1);
                appUserService.updateById(appUser);
                return MessageResult.warpper("000", null, "个人认证信息修改成功");
            }
            return MessageResult.warpper(PromptInfo.ERROR_USER_AUTH_FILED);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return MessageResult.warpper(PromptInfo.ERROR_AUTH_PIC_UPLOAD);
        }
    }

    /**
     * 查询个人认证信息
     */
    @PostMapping("/delete")
    public Object delete(@JwtUser JwtSession session) {
        if (!session.isLogin()) {
            return MessageResult.warpper(PromptInfo.USER_LOGIN_INVALID);
        }
        Long userId = session.userId();
        //检查该用户是否存在认证信息
        List<AppUserAuthentication> appUserAuthentications = appUserAuthenticationService.selectByMap(
                MapBuilder.newMap(2).setParam("user_id", userId).setParam("is_del", 0).ok());
        if (appUserAuthentications.size() > 1) {
            return MessageResult.warpper(PromptInfo.ERROR_USER_AUTH_MORE);
        } else if (appUserAuthentications.size() == 0) {
            return MessageResult.warpper(PromptInfo.ERROR_USER_AUTH_NULL);
        }

        AppUserAuthentication oldAuth = appUserAuthentications.get(0);
        if (oldAuth.getStatus() != 3) {
            return MessageResult.warpper(PromptInfo.ERROR_USER_AUTH_NOT_DEL);
        }
        AppUserAuthentication authentication = new AppUserAuthentication();
        authentication.setId(oldAuth.getId());
        authentication.setIsDel(1);
        authentication.setUpdateTime(new Date());
        if (appUserAuthenticationService.updateById(authentication)) {
            //修改app_user表认证状态
            AppUser appUser = new AppUser();
            appUser.setId(userId);
            appUser.setAuthState(0);
            appUserService.updateById(appUser);
            return MessageResult.warpper("000", null, "个人认证信息删除成功");
        } else {
            return MessageResult.warpper(PromptInfo.ERROR_USER_AUTH_DEL_FILED);
        }
    }

}
